// utils/request.js
import { API_URL } from './config';
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
  });
}
function generateClientInfo() {
  const uuid = uni.getStorageSync('_uuid') || generateUUID();
  uni.setStorageSync('_uuid', uuid); // 存储 UUID

  return JSON.stringify({
      platform: "WeChat",
      device_no: uuid
  });
}
const request = (url, method = 'GET', data = {},action, headers = {}) => {
  return new Promise((resolve, reject) => {
	  console.log(action);
    const isMiniProgram = () => {
      const platform = uni.getSystemInfoSync().platform;
      return platform === 'devtools' || platform === 'mp-weixin' || platform === 'mp-alipay';
    };

    // 获取 Token
    let token = '';
    if (isMiniProgram()) {
      token = uni.getStorageSync('userToken'); // 假设你将 Token 存储在 userToken 中
    }
	//  token ? `Bearer ${token}` : ''
    let clientInfo = uni.getStorageSync('clientInfo');

    if (!clientInfo) {
        clientInfo = generateClientInfo(); // 生成并获取 client-info
        uni.setStorageSync('clientInfo', clientInfo); // 存储 client-info
    }
    // 发起请求
    uni.request({
      url: `${API_URL}${url}`,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        'Authorization':uni.getStorageSync('token'), // 添加 Token
		'token':uni.getStorageSync('token'),
		'client-info':clientInfo,
		...(action ? { 'action': action } : {})
      },
      success: (res) => {
        if (res.statusCode === 200) {
			if(res.data.status==80003){
				uni.showToast({
					title:res.data.msg,
					icon:'none'
				})
				setTimeout(()=>{
					uni.navigateTo({
						url:'/login/auth'
					})
				},1000)
				return
			}else if(res.data.status==10000){
				resolve(res.data);
				return
			}else{
				uni.hideLoading()
				uni.showToast({
					title:res.data.msg,
					icon:'none'
				})
				return
			}
        } else {
          reject(res);
        }
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

export default request;